import formula from "./arithmetic.js"

let common = (function(){
    var findForward = function(stack,findString){
        for(var i=stack.length-1;i>-1;i--){
            if(stack[i] === findString) return i;
        }
        return -1;
    };
    var findBackward = function(stack,findString){
        for(var i=0;i<stack.length;i++){
            if(stack[i] === findString) return i;
        }
        return -1;
    };
    var findForwardCst = function(stack,findHandler){
        for(var i=stack.length-1;i>-1;i--){
            if(findHandler(stack[i])===true) return i;
        }
        return -1;
    };
    var findBackwardCst = function(stack,findHandler){
        for(var i=0;i<stack.length;i++){
            if(findHandler(stack[i])===true) return i;
        }
        return -1;
    };
    var rndNum = function(n){
        var rnd="";
        for(var i=0;i<n;i++)
            rnd+=Math.floor(Math.random()*10);
        return rnd;
    };
    var fullReplace = function(oriStr,dic,iscon){
        var s = oriStr,conStr;
        for(var key in dic){
            var search = new RegExp(key,"ig");
            if(dic[key] === "" && iscon){
                conStr = "''";
            } else if(typeof dic[key] == "string" && iscon){
                conStr = "'"+dic[key]+"'";
            } else{
                conStr = dic[key];
            }
            if(iscon){
                s = s.replace(search,conStr);
            } else {
                s = s.replace(search,dic[key]);
            }
        }
        return s;
    };
    var allReplace = function(oriStr,fromStr,toStr){
        return oriStr.replace(new RegExp(fromStr,'gm'),toStr);
    };
    var trim = function(oriStr){
        return oriStr.replace(/(^\s*)|(\s*$)/g, ""); 
    };
    
    var noQuot = function(str){
        str = str+'';
        str = str.replace(/^'|"/,'').replace(/'|"$/,'');
        // str = str.replace(/\'/g,"");
        // str = str.replace(/\"/g,"");
        return str;
    };
    var noParenthesis = function(str,ifIf){
        if(str.indexOf("(")>-1){
            str = str.substr(str.indexOf("(")+1);
        }
        if(str.lastIndexOf(")") === str.length-1){
            str = str.substr(0,str.lastIndexOf(")"));
        }
        if(ifIf){
            return str.split(',');
        }
        return str.replace(/__ISNUMBER__|__ROUND__/g,'');
    };
    var isNumber = function(val){
    　　if (parseFloat(val).toString() === "NaN") {
            return false; 
    　　}else{
            var arr = val.toString().split("");
            if(arr.length == 0) return false;
            if(typeof val == 'string' && arr.length > 1 && arr[0] === '0'){
                return /^0\.\d+$/g.test(val);
            }
            if(arr[0] === "." || arr[arr.length-1] === ".") return false;
            var dotCount = 0;
            for(var i=0;i<arr.length;i++){
                if(arr[i] === "."){
                    dotCount++;
                    continue;
                }
                if(i==0 && arr[i]==="-"){
                    continue;
                }
                if(parseFloat(arr[i]).toString() === "NaN") 
                    return false;
                
            }
            if(dotCount>1) return false;
    　　　　 return true; 
    　　}
    };
    var isStrNumber = function(val) {
        if(/^\"(.*?)\"$/.test(trim(val))){
            var str = trim(val).replace(/^\"|\"$/g,'');
            if(isNumber(str)){
                val = str;
            }
        } else if(/^\'(.*?)\'$/.test(trim(val))){
            var str = trim(val).replace(/^\'|\'$/g,'');
            if(isNumber(str)){
                val = str;
            }
        }
        if (parseFloat(val).toString() === "NaN") {
    　　　　return false; 
    　　}else{
            var arr = val.toString().split("");
            if(arr.length == 0) return false;
            if(arr[0] === "." || arr[arr.length-1] === ".") return false;
            var dotCount = 0;
            for(var i=0;i<arr.length;i++){
                if(arr[i] === "."){
                    dotCount++;
                    continue;
                }
                if(i==0 && arr[i]==="-"){
                    continue;
                }
                if(parseFloat(arr[i]).toString() === "NaN") 
                    return false;
                
            }
            if(dotCount>1) return false;
    　　　　 return true; 
    　　}
    }
    //驼峰命名转换指定字符间隔形式
    var camelCaseToLowerLine = function(oritext,separator){
        var temp = oritext.replace(/[A-Z]/g, function (match) {	
            return separator + match.toLowerCase();
          });
          //如果首字母是大写，执行replace时会多一个_，这里需要去掉
          if(temp.slice(0,1) === separator){
              temp = temp.slice(1);
          }
        return temp;
    };

    var getValues = function(obj){
        var vals = [];
        for(var key in obj){
            vals.push(obj[key]);
        }
        return vals;
    };    

    var isUnknownValue = function(val){
        return val.toLowerCase() == "_unknown_value_";
    };

    var unknownValue = function(){
        return "_unknown_value_";
    };
    // round函数补0操作
    var buZero = function(num,n){
        var f = parseFloat(num);
        if(isNaN(f)){
            return false;
        } 
        var s = f.toString();
        var rs = s.indexOf('.');
        //判定如果是整数，增加小数点再补0
        if(rs < 0 && n > 0){
            rs = s.length;
            s += '.'; 
        }
        while(s.length <= rs + n){
            s += '0';
        }
        return s   
    }
    // 判断是否科学计数法
    var isScience = function(num){
        var regu = /^[+-]?[\d]+([\.][\d]+)?([Ee][+-]?[\d]+)?$/
        if(new RegExp(regu).test(num)){
            return true
        }
        return false
    }
    // 四舍五入保留两位小数 num金额 n小数位
    var fomatFloat = function (num,n){   
        var isCnInfu = false
        var f = parseFloat(num);
        // 判断是否为负数
        if (num < 0) {
            // 转正整数
            num = Math.abs(num)
            isCnInfu = true
        } 
        n = parseInt(n)
        if(isNaN(f)){
            return false;
        }   
        f = Math.round(num*Math.pow(10, n))/Math.pow(10, n); // n 幂  
        if(n < 0){
            var s = f.toString();
            return isCnInfu ? '-'+s : s+'';
        } else {
            var s = f.toString();
            var rs = s.indexOf('.');
            //判定如果是整数，增加小数点再补0
            if(rs < 0 && n > 0){
                rs = s.length;
                s += '.'; 
            }
            while(s.length <= rs + n){
                s += '0';
            }
            return isCnInfu ? '-'+s : s+'';
        }
    }  
    var roundNum = function (str){
        var arr =  str.split(',');
        // 计算出结果
        var number = 0
        if(isNumber(arr[0])){
            number =  arr[0]*1
        } else if (arr[0]==="''"){
            return  ''
        } else{
            // 把空格替换成0
            number = eval(arr[0])
            if(isNaN(number)){
                return false
            } else if (!isFinite(number)){
                return false
            }
            
        }
        // 转成int型
        var number_digits = 0
        if(isNumber(arr[1])){
            number_digits = parseInt(arr[1])
        }
        return fomatFloat(number,number_digits)
    }
    var evalExpression = function(condition){
        if(condition.indexOf('__ISNUMBER__') != -1){
            condition = eval(condition.replace(/__ISNUMBER__|__ROUND__/g,'').replace(/≥/g,">=").replace(/≤/g,"<=").replace(/≠/g,"!="));
            condition = Number(condition);
            
        }else if(isNumber(condition)){
            condition = false;
        }else{
            condition = eval(condition.replace(/≥/g,">=").replace(/≤/g,"<=").replace(/≠/g,"!="));
        }
        return condition;
    };
    //获取IF的值
    var getIF = function(arr) {
        var condition = arr[0],
            trueValue = arr[1],
            falseValue = arr[2];
        if(typeof condition == 'string'){
            // 表达式中有包含不包含
            if(condition.indexOf('⊇') != -1 || condition.indexOf('⊉') != -1){
                condition = condition.replace(/([^⊇⊉]+)([⊇⊉])([^⊇⊉]+)/ig,function(a,b,c,d){
                    b = eval(b.replace(/__ISNUMBER__|__ROUND__/g,'').replace(/≥/g,">=").replace(/≤/g,"<=").replace(/≠/g,"!="));
                    d = eval(d.replace(/__ISNUMBER__|__ROUND__/g,'').replace(/≥/g,">=").replace(/≤/g,"<=").replace(/≠/g,"!="));
                    return (c == '⊇') ? (((b||'')+'').indexOf(d) != -1) : (((b||'')+'').indexOf(d) == -1);
                });
            }else{
                condition = evalExpression(condition);
            }
        }

        if(typeof trueValue == 'string'){
            if(trueValue.indexOf('__ISNUMBER__') != -1){
                trueValue = trueValue.replace(/__ISNUMBER__/g,'');
            }
        }
        if(typeof falseValue == 'string'){
            if(falseValue.indexOf('__ISNUMBER__') != -1){
                falseValue = falseValue.replace(/__ISNUMBER__/g,'');
            }
        }
        if(/['|"][\d\D]+['|"]/.test(condition)){
            condition = noQuot(condition)
        }
        if(trueValue != "''" && !/['|"][\d\D]+['|"]/.test(trueValue) && !isNumber(trueValue) && !formula.arithmetic.isArithmetical(trueValue,true)){
            trueValue = ("'"+trueValue+"'");
        }
        if(falseValue != "''" && !/['|"][\d\D]+['|"]/.test(falseValue) && !isNumber(falseValue) && !formula.arithmetic.isArithmetical(falseValue,true)){
            falseValue = ("'"+falseValue+"'");
        }
        if(typeof condition == 'string'){
            return condition.toLowerCase() == "true" ? trueValue : falseValue;
        }
        return condition ? trueValue : falseValue;
    }

    function DATEDIFF(datepart,startdate,enddate){
        var datepart = (datepart || "d").replace(/'/g,'').toLowerCase(),reg = /\d{4}-\d{1,2}-\d{1,2}|\d{4}-\d{1,2}/,res = 0;
        var str_start = (startdate||"").replace(/\//g,"-").match(reg),end_str = (enddate||"").replace(/\//g,"-").match(reg);
        if(str_start && end_str){
            var startDate = new Date(str_start[0].replace(/-/g,"/"));
            var enddate = new Date(end_str[0].replace(/-/g,"/"));
            if(datepart == "m"){
                res =  (enddate.getFullYear() - startDate.getFullYear())*12 + (enddate.getMonth()-startDate.getMonth())
            }else if(datepart == "d"){
                res =  Math.round(((+enddate)-(+startDate))/1000/60/60/24);
            }else if(datepart == "y"){
                res = (enddate.getFullYear() - startDate.getFullYear());
            }
        }else{
            res = '';
        }
        return res;
    };

    var getDateDiff = function(arr){
        var datepart = arr[0],
            startdate = arr[1],
            enddate = arr[2];
        return DATEDIFF(datepart,startdate,enddate);
    };
    // 金额转换中文大写
    var convertCurrency = function(money) {
        // 负数标识
        var cnInfu = ''
        // 判断是否为负数
        if (money < 0) {
            // 转正整数
            money = Math.abs(money)
            cnInfu = '负'
        }
        // 四舍五入保留两位小数
        money = fomatFloat(money, 2)
        //汉字的数字
        var  cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        //基本单位
        var cnIntRadice = new Array('', '拾', '佰', '仟');
        //对应整数部分扩展单位
        var cnIntUnits = new Array('', '万', '亿', '兆');
        // var cnIntUnits = new Array('', '万', '亿', '万'); // 特殊处理
        //对应小数部分单位
        var cnDecUnits = new Array('角', '分', '毫', '厘');
        //整数金额时后面跟的字符
        var cnInteger = '整';
        //整型完以后的单位
        var cnIntLast = '元';
        //最大处理的数字
        var maxNum = 999999999999.99;
        //金额整数部分
        var integerNum;
        //金额小数部分
        var decimalNum;
        //输出的中文金额字符串
        var chineseStr = '';
        //分离金额后用的数组，预定义
        var parts;
        if (money === '') { return ''; }
        money = parseFloat(money);
        if (money > maxNum) {
            //超出最大处理数字
            return '';
        }
        if (money == 0) {
            chineseStr = cnNums[0] + cnIntLast + cnInteger;
            return chineseStr;
        }
        //转换为字符串
        money = money.toString();
        if (money.indexOf('.') == -1) {
            integerNum = money;
            decimalNum = '';
        } else {
            parts = money.split('.');
            integerNum = parts[0];
            decimalNum = parts[1].substr(0, 4);
        }
        //获取整型部分转换
        if (parseInt(integerNum, 10) > 0) {
            var zeroCount = 0;
            var IntLen = integerNum.length;
            for (var i = 0; i < IntLen; i++) {
            var n = integerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n == '0') {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                chineseStr += cnNums[0];
                }
                //归零
                zeroCount = 0;
                chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m == 0 && zeroCount < 4) {
                chineseStr += cnIntUnits[q];
            }
            }
            chineseStr += cnIntLast;
        }
        //小数部分
        if (decimalNum != '') {
            var decLen = decimalNum.length;
            for (var i = 0; i < decLen; i++) {
                var n = decimalNum.substr(i, 1);
                if (n != '0') {
                    chineseStr += cnNums[Number(n)] + cnDecUnits[i];
                }else{
                    if(integerNum > 0){
                        chineseStr += '零'
                    }
                }
            }
        }
        if (chineseStr == '') {
            chineseStr += cnNums[0] + cnIntLast + cnInteger;
        } else if (decimalNum == '') {
            chineseStr += cnInteger;
        }
        return cnInfu + chineseStr;
      }

    return {
        findForward:findForward,
        findBackward:findBackward,
        findForwardCst:findForwardCst,
        findBackwardCst:findBackwardCst,
        rndNum:rndNum,
        fullReplace:fullReplace,
        allReplace:allReplace,
        trim:trim,
        isNumber:isNumber,
        isStrNumber:isStrNumber,
        noQuot:noQuot,
        noParenthesis:noParenthesis,
        camelCaseToLowerLine:camelCaseToLowerLine,
        getValues:getValues,
        isUnknownValue:isUnknownValue,
        unknownValue:unknownValue,
        convertCurrency:convertCurrency,
        isScience:isScience,
        roundNum:roundNum,
        buZero:buZero,
        getIF:getIF,
        getDateDiff:getDateDiff
    };
})();

// String.prototype.getParams = function(paramCount){
//     if(typeof paramCount === "undefined") paramCount = 0;
//     var arr = this.split(",");
//     var params = [];
//     if(arr.length >= paramCount){
//         var len = arr.length;
//         for(var i=len;i>len-paramCount+1;i--){
//             var item = arr.pop();
//             params.unshift(item);
//         }
//         if(arr.length>0){
//             params.unshift(arr.join(","));
//         }
//         return params;
//     }else{
//         return arr;
//     }
// };

String.prototype.getParams = function(){
    var reg = /\'(.*?)\'/g;
    var params = [];
    var s = this.toString();
    s = s.replace(/__ISNUMBER__|__ROUND__/g,'');
    var arr = s.match(reg);
    if(arr!==null && arr.length>0){
        arr.forEach(function(item){
            var i = item.split(",").join("|");
            s = s.replace(item,i);
        });
    }
    arr = s.split(",");
    arr.forEach(function(item){
        params.push(item.split("|").join(","));
    });
    return params;
};

String.prototype.getJsonArrParams = function(){
    var reg = /\'(\[(.+?)\]?)?\'/g;
    return this.match(reg);
};

String.prototype.replaceAll = function(fromStr,toStr){
    return this.replace(new RegExp(fromStr,'gm'),toStr);
};

export {common}